<template>
  <div class="xtx-pagination">
    <a href="javascript:;" v-if="myCurrentPage > 1" @click="changePager(myCurrentPage-1)">上一页</a>
    <a href="javascript:;" class="disabled" v-else>上一页</a>
    <span v-if="pager.start > 1">...</span>
    <a href="javascript:;" v-for="i in pager.btnArr" :key="i" :class="{ active: i === myCurrentPage}"
      @click="changePager(i)">{{ i }}</a>
    <span v-if="pager.end < pager.pageCount">...</span>
    <a href="javascript:;" v-if="myCurrentPage < pager.pageCount" @click="changePager(myCurrentPage+1)">下一页</a>
    <a href="javascript:;" v-else class="disable">下一页</a>
  </div>
</template>
<script>
import { ref, computed, watch } from 'vue'

export default {
  name: 'XtxPagination',
  props: {
    // 按钮个数
    count: {
      type: Number,
      default: 5
    },
    total: {
      type: Number,
      default: 100
    },
    pageSize: {
      type: Number,
      default: 10
    },
    currentPage: {
      type: Number,
      default: 1
    }
  },

  setup (props, context) {
    const myCurrentPage = ref(1)
    const myTotal = ref(100)
    const myPageSize = ref(10)

    const pager = computed(() => {
      // 总页数
      const pageCount = Math.ceil(myTotal.value / myPageSize.value)
      // 按钮个数以及当前页码
      const offset = Math.floor(props.count / 2)
      let start = myCurrentPage.value - offset
      let end = start + (props.count - 1)
      if (start < 1) {
        start = 1
        end = (start + props.count - 1) > pageCount ? pageCount : (start + props.count - 1)
      }
      if (end > pageCount) {
        end = pageCount
        start = (end - props.count + 1) < 1 ? 1 : (end - props.count + 1)
      }
      const btnArr = []
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      return {
        pageCount, btnArr, start, end
      }
    })

    watch(props, () => {
      myTotal.value = props.total
      myPageSize.value = props.pageSize
      myCurrentPage.value = props.currentPage
    }, { immediate: true })

    // 切换分页
    function changePager (page) {
      myCurrentPage.value = page
      context.emit('current-page', page)
    }

    return {
      myCurrentPage, myTotal, myPageSize, pager, changePager
    }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;

  >a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;

    &:hover {
      color: @xtxColor;
    }

    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }

    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;

      &:hover {
        color: #333
      }
    }
  }

  >span {
    margin-right: 10px;
  }
}
</style>
